// pages/seal/fileUploadDetail/fileUploadDetail.js
import config from '../../../utils/config';

Page({
  data: {
    orderId: '',
    type: '',
    name: '',
    nameRemark: '',
    require: false,
    isUpload: false,
    filePath: '',
    uploading: false
  },

  onLoad(options) {
    const { type = '', orderId = '' } = options;
    this.setData({ type, orderId });
    if (!type || !orderId) {
      wx.showToast({ title: '参数缺失', icon: 'none' });
      return;
    }
    this.fetchDetail(type, orderId);
  },

  // 获取单项详情
  fetchDetail(type, orderId) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    wx.request({
      url: `${config.baseUrl}/seal/getUploadFileList`,
      method: 'GET',
      data: { orderId },
      header: {
        'Authorization': token,
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          // 遍历查找type对应的项
          let found = null;
          (res.data.data || []).forEach(group => {
            (group.child || []).forEach(item => {
              if (item.key === type) found = item;
            });
          });
          if (found) {
            this.setData({
              name: found.name,
              nameRemark: found.nameRemark || '',
              require: found.require,
              isUpload: found.isUpload,
              filePath: found.filePath || ''
            });
          } else {
            wx.showToast({ title: '未找到对应项', icon: 'none' });
          }
        } else {
          wx.showToast({ title: res.data.msg || '获取数据失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 选择图片或视频
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFile = res.tempFiles[0];
        const tempFilePath = tempFile.tempFilePath;
        const isVideo = tempFile.fileType === 'video';
        this.setData({ uploading: true });
        // 上传到后端
        const token = wx.getStorageSync('token');
        if (!token) {
          wx.showToast({ title: '请先登录', icon: 'none' });
          this.setData({ uploading: false });
          return;
        }
        wx.uploadFile({
          url: `${config.baseUrl}/seal/uploadFile`,
          filePath: tempFilePath,
          name: 'file',
          formData: {
            orderId: this.data.orderId,
            type: this.data.type
          },
          header: {
            'Authorization': token
          },
          success: (uploadRes) => {
            let data = uploadRes.data;
            try {
              data = typeof data === 'string' ? JSON.parse(data) : data;
            } catch (e) {}
            if (data && data.code === 200 && data.data && data.data.url) {
              this.setData({
                filePath: data.data.url,
                isUpload: true
              });
              wx.showToast({ title: '上传成功', icon: 'success' });
              // 上传成功后自动执行提交逻辑
              this.handleSubmit();
            } else {
              wx.showToast({ title: data.msg || '上传失败', icon: 'none' });
            }
          },
          fail: () => {
            wx.showToast({ title: '上传失败', icon: 'none' });
          },
          complete: () => {
            this.setData({ uploading: false });
          }
        });
      }
    });
  },

  // 提交处理逻辑
  handleSubmit() {
    const { filePath, name, require } = this.data;
    if (require && !filePath) {
      wx.showToast({ title: `请上传${name}`, icon: 'none' });
      return;
    }
    
    // 直接执行提交逻辑，无需额外延迟
    wx.showToast({
      title: '提交成功',
      icon: 'success',
      duration: 2000,
      success: () => {
        setTimeout(() => {
          // 本地更新上个页面的groupList
          const pages = getCurrentPages();
          if (pages.length > 1) {
            const prevPage = pages[pages.length - 2];
            const { groupList } = prevPage.data;
            const { type, filePath } = this.data;
            // 遍历找到对应项并更新
            for (let i = 0; i < groupList.length; i++) {
              const group = groupList[i];
              for (let j = 0; j < (group.child || []).length; j++) {
                const item = group.child[j];
                if (item.key === type) {
                  item.isUpload = true;
                  item.filePath = filePath;
                }
              }
            }
            prevPage.setData({ groupList });
          }
          wx.navigateBack();
        }, 2000);
      }
    });
  }
});